package com.lagou.connect;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author: wudong
 * @create: 2021-05-19 14:02
 **/
public class DefaultConectionManager implements ConectionManager {
    protected DataSource dataSource;
    private Connection connection;
    protected TransactionIsolationLevel level;
    private boolean autoCommit;
    private Integer originTransactionIsolation;

    public DefaultConectionManager(DataSource dataSource,TransactionIsolationLevel level, boolean autoCommit) {
        this.dataSource = dataSource;
        this.autoCommit = autoCommit;
        this.level = level;
    }


    @Override
    public Connection getConnection() throws SQLException {
        if(connection == null){
            connection = dataSource.getConnection();
            if(connection.getAutoCommit() != autoCommit){
                connection.setAutoCommit(autoCommit);
            }
            if(level != null){
                originTransactionIsolation = connection.getTransactionIsolation();
                connection.setTransactionIsolation(level.getLevel());
            }
        }
        return connection;
    }

    @Override
    public void commit() throws SQLException {
        if(connection != null && !connection.getAutoCommit()){
            connection.commit();
        }
    }

    @Override
    public void rollback() throws SQLException {
        if(connection != null && !connection.getAutoCommit()){
            connection.rollback();
        }
    }

    @Override
    public void close() throws SQLException {
        if(connection != null){
            connection.setAutoCommit(true);
            if(originTransactionIsolation != null){
                connection.setTransactionIsolation(originTransactionIsolation);
            }
            connection.close();
        }
    }
}
